using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Kingzad.MicroService.BusinessCore.Providers;
using MassTransit;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace MicroService
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            // Add Cache
            ConfigCache(services);
            // Add MassTransit
            ConfigMassTransit(services);
            // Add Swagger
            ConfigSwagger(services);
            // Add DI
            ConfigDependInjection(services);
            // Add HttpClient Factory
            ConfigureHttpClient(services);
            // Add MassTransity IBus
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            LogConfig(logger);

            UseSwagger(app);

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }

        //Dependency Injection for application services
        private static void ConfigDependInjection(IServiceCollection services)
        {
            // DI for provider
            services.AddSingleton<ISqlConnectionFactory, SqlConnectionFactory>();
            services.AddSingleton<ISqlServerProvider, SqlServerProvider>();
            services.AddSingleton<IMongoConnectionFactory, MongoConnectionFactory>();
            services.AddSingleton<ICacheProvider, CacheProvider>();
            services.AddSingleton<IHttpClientProvider, HttpClientProvider>();
            services.AddSingleton<IMassTransitProvider, MassTransitProvider>();

            // DI for repository

            // DI for Service

            // DI for presentation

        }

        private void ConfigSwagger(IServiceCollection services)
        {
            // Add Swagger
            services.AddSwaggerGen();
        }

        private void UseSwagger(IApplicationBuilder app)
        {
            // Enable middleware to serve generated Swagger as a JSON endpoint
            app.UseSwagger();

            // Enable middleware to serve swagger-ui assets (HTML, JS, CSS etc.)
            //app.UseSwaggerUI(SwaggerConfig.SetupSwaggerUiOptions());
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Micro Service API V1");
            });
        }

        private void ConfigCache(IServiceCollection services)
        {
            //if (_env.IsEnvironment("IntegrationTests") || !_cmaOptions.RedisEnabled)
            services.AddDistributedMemoryCache();
            //else
            //    services.AddDistributedRedisCache(Configuration);
        }

        private void ConfigureHttpClient(IServiceCollection services)
        {
            //var _SettingsOptions = Configuration.GetSection("FacebookServiceOptions").Get<FacebookServiceOptions>();

            //services.AddTransient<ICertificateHelper, CertificateHelper>();

            services.AddHttpClient("ExternalServceApi", client =>
            {
                client.BaseAddress = new Uri("http://test1.url/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            }).ConfigurePrimaryHttpMessageHandler((provider) => new HttpClientHandler
            {
                //ServerCertificateCustomValidationCallback = (provider.GetService<ICertificateHelper>()).ServerCertificateCustomValidationCallback
            });
        }

        private void ConfigMassTransit(IServiceCollection services)
        {
            // InMemory
            // services.AddSingleton(provider => Bus.Factory.CreateUsingInMemory(cfg => { }));

            //RabbigMQ
            services.AddSingleton(provider => Bus.Factory.CreateUsingRabbitMq(cfg => {
                cfg.Host("127.0.0.1", "/", h =>
                {
                    h.Username("guest");
                    h.Password("guest");
                });

                cfg.ReceiveEndpoint("channelNanme", e => {
                    //Response Handler
                    e.Consumer(() => new ResponseHandler());
                    //Subscribe Handler
                    e.Handler<string>(async context => {
                        await (new SubscribeHandler()).Consume(context);
                    });
                });
            }));

            services.AddSingleton<IBus>(provider => provider.GetRequiredService<IBusControl>());
        }

        private void LogConfig(ILogger logger)
        {
            //var loggingOptions = Configuration.GetSection("LoggingOptions").Get<LoggingOptions>();
            //logger.LogInformation($"LoggingOptions:RollingFile:Enabled = {loggingOptions.RollingFile.Enabled}");
            //if (loggingOptions.RollingFile.Enabled)
            //    logger.LogInformation($"LoggingOptions:RollingFile:Filepath = {loggingOptions.RollingFile.FilePath}");

        }
    }
}
